# -*- coding: utf-8 -*-
import hashlib
import json
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'yUMnQdkpUe': {  # 支付宝 H5
        'API_KEY': 'b3b85d8bc035b76ce34ed88482e5f7e6',
        'gateway': 'https://yahoo.vdian365.com/api_deposit.shtml',
        'query_gateway': 'https://yahoo.vdian365.com/api_query.shtml',
    },
    'V7mrMcRCnk': {  # 智慧云 支付宝H5 2% 50-10000 dwc
        'API_KEY': '9f1d9f766297853705d143d29cba289c',
        'gateway': 'https://yahoo.vdian365.com/api_deposit.shtml',
        'query_gateway': 'https://yahoo.vdian365.com/api_query.shtml',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = urllib.urlencode(sorted(parameter.items()))
    s += '&Key={}'.format(key)
    _LOGGER.info('zhihuipay sign : %s', s)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().lower()
    return sign


def generate_query_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'Key={}'.format(key)
    _LOGGER.info('zhihuipay query sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('Sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("zhihuipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    """ 支付宝H5 """
    if service == 'alipay_scan':
        return '8'
    elif service == 'alipayh5':
        return '9'
    else:
        return '9'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('Mode', _get_pay_type(service)),
        ('CustomerId', str(pay.id)),  # 商户订单号
        ('BankCode', 'ALIPAY'),
        ('Money', str(int(pay_amount))),
        ('UserId', app_id),  # 商户号merno
        ('CallBackUrl', '{}/pay/api/{}/zhihuipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    url = _get_gateway(app_id)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("zhihuipay create: url: %s, %s", url, json.dumps(parameter_dict))
    response = requests.post(url, data=parameter_dict, headers=headers, timeout=5, verify=False)
    _LOGGER.info("zhihuipay create: response: %s", json.dumps(response.text))
    data = json.loads(response.text)['Data']
    order_db.fill_third_id(pay.id, data['OrderId'])
    return {'charge_info': data['Url']}


# OK
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("zhihuipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['CustomerId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zhihuipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['Status'])
    trade_no = data['OrderId']
    total_fee = float(data['Money'])
    trade_time = str(data['Time'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'trade_time': trade_time
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('zhihuipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    url = _get_query_gateway(app_id)
    api_key = _get_api_key(app_id)
    _LOGGER.info(u'zhihuipay query: %s', url)

    dct = OrderedDict((
        ('CustomerId', str(pay_id)),  # 订单号
        ('OrderType', 1),  # 固定值 1 ，表示充值订单
        ('UserId', app_id),
    ))
    dct['Sign'] = generate_query_sign(dct, api_key)

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info(u'zhihuipay query data: %s', dct)
    response = requests.post(url, data=dct, headers=headers, timeout=5)
    _LOGGER.info(u'zhihuipay query rsp: %s', response.text)
    data = json.loads(response.text)
    _LOGGER.info('zhihuipay query order response: {}'.format(data))

    if response.status_code == 200:
        trade_status = str(data['Status'])
        total_fee = float(data['Data']['Money'])
        trade_no = data['Data']['OrderId']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status:
            _LOGGER.info('zhihuipay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('zhihuipay data error, status_code: %s', response.status_code)
